<template>
	<view class="page-wx-login">
		<image class="logo" :src="config.logo" mode="scaleToFill"></image>
		<button class="login-btn" :class="openBtn ? '' : 'disabled'" :disabled="!openBtn"  @click="handleLogin" type="primary" :loading="loginLoading">
		    <image class="wx-img" src="../../static/images/wx_logo.png" mode="aspectFit"></image>
		    <view class="btn-title">微信用户一键登录</view>
		</button>
	</view>
</template>

<script>
	let vm;
	export default {
		data() {
			return {
				config: {
					logo: ''
				},
				openBtn: true,
				loginLoading: false
			}
		},
		onLoad() {
			vm = this;
			const pages = getCurrentPages();
			const page = (pages[pages.length - 1]).route;
			if(this.isLogin) {
				uni.reLaunch({
					url: '/pages/index/index'
				})
				return
			}
		},
		onShow() {
			uni.hideHomeButton()
		},
		methods: {
			async handleLogin() {
				const [userErr, userRes] = await uni.getUserProfile({
					desc: '用于完善用户资料',
				});
				const [loginErr, loginRes] = await uni.login({provider: 'weixin'});
				if(loginErr) {
					uni.showToast({
						title: '获取微信授权失败',
						icon: 'none'
					})
					return
				}
				const reqData = {
					jsCode: loginRes.code,
					iv: userRes.iv,
					encryptedData: userRes.encryptedData,
				}
				const [res, err] = await vm.$post('xcx/wxLogin', reqData);
				console.log(res)
				if(err || !res.data) {
					uni.showToast({
						title: '获取微信用户信息失败,请稍后重试',
						icon: 'none'
					})
					return
				}
				if(res.data.phone) {
					vm.setState({
						isLogin: true,
						userInfo: {
							userName: res.data.userName,
							headImg: res.data.headImg,
							uid: res.data.uid,
							openId: res.data.xcxOpenId,
							realName: res.data.realName,
							cmId: res.data.cmId,
							aid: res.data.aid,
							area: res.data.area,
							company: res.data.company,
							cmId: res.data.cmId
						}
					})
					uni.reLaunch({
						url: '/pages/index/index'
					})
				}else {
					uni.reLaunch({
						url: `/pages/login/login?userName=${res.data.userName}&headImg=${res.data.headImg}&uid=${res.data.uid}&openId=${res.data.xcxOpenId}`
					})
				}
			}
		}
	}
</script>

<style lang="less">
	.page-wx-login {
		width: 100%;
		height: 100%;
		background-repeat: no-repeat;
		background-size: 100% auto;
		display: flex;
		flex-direction: column;
		
		.logo {
			width: 356rpx;
			height: 100rpx;
			margin: 200rpx auto;
		}
		
		.login-btn {
			width: 690rpx;
			height: 94rpx;
			background: #1AAD19;
		    display: flex;
		    justify-content: center;
		    align-items: center;
			transform: translateY(-50%);
		
		    .wx-img {
		        width: 50rpx;
		        height: 50rpx;
		    }
		
		    .btn-title {
		        margin-left: 20rpx;
				color: #ffffff;
		    }
		}
		
		.disabled {
		    background-color: #aaa;
		    color: #fff;
		}

	}
</style>
